package com.authine.cloudpivot.ext.controller.upload;

import com.authine.cloudpivot.engine.api.facade.FileStoreFacade;
import com.authine.cloudpivot.engine.api.model.runtime.AttachmentModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.ext.Utils.FormDataFileUpload;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * @author fengjie
 * @version 1.0.0
 * @ClassName FileUploadController
 * @Description 文件上传到优米云盘
 * @createTime 2023/2/10 10:15
 */
@Slf4j
@RestController
@RequestMapping("/public/ext/upload")
public class FileUploadController extends BaseController {


    @Autowired
    private FileStoreFacade fileStoreFacade;

    /**
     * 上传优米云盘
     * @param objId                 业务id
     * @param schemaCode            模型编码
     * @param childSchemaCode       子表模型编码
     * @param attachmentFiled       附件字段
     * @return
     * @throws Exception
     */
    @GetMapping("uploadToCloudDisk")
    public ResponseResult<Void> uploadToCloudDisk(String objId, String schemaCode, String childSchemaCode, String attachmentFiled) throws Exception {

        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(schemaCode, objId);
        // 获取子表数据
        List<Map<String,Object>> childList = (List<Map<String,Object>>)bizObject.get(childSchemaCode);
        AttachmentModel attachment;
        InputStream inputStream;
        File tempFile;
        FileOutputStream outputStream;
        if (CollectionUtils.isNotEmpty(childList)) {
            for (Map<String,Object> childMap :childList) {
                // 获取附件信息
                List<Map<String,Object>> attachmentList = (List<Map<String,Object>>)childMap.get(attachmentFiled);
                if (CollectionUtils.isNotEmpty(attachmentList)) {
                    for (Map<String,Object> bizAttachment : attachmentList) {
                        // 通过附件refId查询附件表
                        attachment = getBizObjectFacade().getAttachmentByRefId((String) bizAttachment.get("refId"));
                        // 获取附件的文件流
                        inputStream = fileStoreFacade.downloadFile(attachment.getRefId());
                        int size = inputStream.available();
                        int lastIndexOf = attachment.getName().lastIndexOf(".");
                        // 获取附件后缀，如.xls，.pdf
                        String suffix = attachment.getName().substring(lastIndexOf);
                        tempFile = File.createTempFile(attachment.getName().substring(0, lastIndexOf), suffix);
                        outputStream = new FileOutputStream(tempFile);
                        // 将文件流写入到临时文件中
                        int ch;
                        while ((ch = inputStream.read()) != -1) {
                            outputStream.write(ch);
                        }
                        // 获取文件中文名称
                        String fileName = attachment.getName().substring(0, attachment.getName().indexOf(" "));
                        String remarks;
                        // 获取备注
                        if (attachment.getName().indexOf("，") > -1) {
                            remarks = attachment.getName().substring(attachment.getName().indexOf(' '),attachment.getName().indexOf('，')).trim();
                        } else {
                            remarks = attachment.getName().split(" ")[1];
                        }
                        String result = FormDataFileUpload.fileUpload(tempFile, size, fileName,suffix, remarks);
                        log.info("附件上传返回结果：{}", result);
                    }
                }
            }
        }
        return this.getOkResponseResult("附件上传优米云盘成功") ;
    }
}
